package com.example.mq.mqserver.core;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

@Data
public class Exchange {
    private String name;
    //交换机类型：Direct、Fanout、Topic、(Header)
    //默认为 Direct交换机
    private ExchangeType type = ExchangeType.DIRECT;
    //是否可持久化,即要不要存在硬盘上
    private boolean durable = false;
    //是否自动删除
    private boolean autoDelete = false;
    //可选参数
    private Map<String, Object> arguments = new HashMap<>();

    //当mybatis存储对象时会调用get方法,此处将对象进行序列化，存到数据库中
    public String getArguments() {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(arguments);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "{}";
    }

    //进行查询操作时,会调用set方法赋值,此处进行反序列化成对象
    public void setArguments(String arguments) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            this.arguments = objectMapper.readValue(arguments, new TypeReference<Map<String, Object>>() {});
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void setArguments(Map<String, Object> arguments) {
        this.arguments = arguments;
    }

    public Object getArgument(String key){
        return arguments.get(key);
    }

    public boolean isDurable() {
        return durable;
    }

    public void setDurable(boolean durable) {
        this.durable = durable;
    }
}
